package org.example.filter;

import com.alibaba.fastjson.JSONObject;
import org.example.constant.AuthConstants;
import org.example.model.SecurityUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Component
public class TokenTranslationFilter extends OncePerRequestFilter {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {

        String authorization = request.getHeader(AuthConstants.AUTHORIZATION);

        if (StringUtils.hasText( authorization)){
            String token = "";
            if (StringUtils.hasText(authorization) && authorization.startsWith(AuthConstants.BEARER)){
                token = authorization.replace(AuthConstants.BEARER, "");
            }
            if (StringUtils.hasText(token) && authorization.startsWith(AuthConstants.MINIBEARER)){
                token = authorization.replace(AuthConstants.MINIBEARER, "");
            }
            if (StringUtils.hasText(token)){
                // 续签token
                Long expire = stringRedisTemplate.getExpire(AuthConstants.LOGIN_TOKEN_PREFIX + token);
                if (expire < AuthConstants.TOKEN_EXPIRE_THRESHOLD_TIME){
                    // 续签
                    stringRedisTemplate.expire(AuthConstants.LOGIN_TOKEN_PREFIX + token, AuthConstants.token_time, TimeUnit.SECONDS);
                }
                // 从redis中获取json格式字符串用户信息
                String userJson = stringRedisTemplate.opsForValue().get(AuthConstants.LOGIN_TOKEN_PREFIX + token);
                //将json格式字符串的认证用户信息转换为认证用户对象
                SecurityUser securityUser = JSONObject.parseObject(userJson, SecurityUser.class);

                Set<SimpleGrantedAuthority> collect =securityUser.getPerms().stream().map(SimpleGrantedAuthority::new).collect(Collectors.toSet());

                UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(securityUser, null, collect);

                SecurityContextHolder.getContext().setAuthentication(authenticationToken);
            }
        }
        filterChain.doFilter(request, response);
    }
}
